/****************************************************************************
 * 2025.8 小庆永不失眠
 ****************************************************************************/

using QAssetBundle;
using QFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

namespace ProjectSurvivor
{
    public partial class CoinUpgradePanel : UIElement, IController
    {
        
        private void Awake()
        {

            foreach (var coinUpgradeitem in this.GetSystem<CoinUpgradeSystem>().Items.Where((item) => !item.UpgradeFinish))
            {
                CoinUpgradeItemTemplate.InstantiateWithParent(CoinUpgradeItemRoot).Self((self) =>
                {
                    var itemChche = coinUpgradeitem;
                    self.GetComponentInChildren<Text>().text = coinUpgradeitem.Description + coinUpgradeitem.Price + "金币";
                    self.onClick.AddListener(() =>
                    {
                        itemChche.UpGrade();
                        AudioKit.PlaySound("Level_up");
                    });
                    var selfCache = self;

                    coinUpgradeitem.OnChanged.Register(()=>
                    {
                        if(itemChche.ConditionCheck())
                        {
                            selfCache.Show();
                        }
                        else
                        {
                            selfCache.Hide();
                        }
                    }).UnRegisterWhenGameObjectDestroyed(selfCache);

                    if (itemChche.ConditionCheck())
                    {
                        selfCache.Show();
                    }
                    else
                    {
                        selfCache.Hide();
                    }
                    Global.Coin.RegisterWithInitValue(coin =>
                    {
                        CoinText.text = "金币:" + coin;
                        if (coin >= itemChche.Price)
                        {
                            selfCache.interactable = true;
                        }
                        else
                        {
                            selfCache.interactable = false;
                        }
                    }).UnRegisterWhenGameObjectDestroyed(self);
                });
            }
            CoinUpgradeItemTemplate.Hide();
            BtnClose.onClick.AddListener(() =>
            {
                this.Hide();
                AudioKit.PlaySound(Sfx.BUTTONCLICK);
            });
        }

        protected override void OnBeforeDestroy()
        {
        }

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}